﻿#region "Copyright (C) Lenny Granovsky. 2011-2013"
//    This library provides extended cache capabilities to the ASP.NET applications.
//
//                Copyright (C) Lenny Granovsky. 2011-2013. 
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 2 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
//    This program comes with ABSOLUTELY NO WARRANTY.
//    This is free software, and you are welcome to redistribute it
//    under certain conditions;
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web;
using System.Collections;

namespace FlexiCache
{
    /// <summary>
    /// SessionOnDemandModule class is responsible for initialization and saving SessionOnDemand data.
    /// </summary>
    public class SessionOnDemandModule : IHttpModule
    {
        /// <summary>
        /// Default constructor.
        /// </summary>
        public SessionOnDemandModule()
        {
        }

        public void Dispose()
        {
        }

        /// <summary>
        /// Method initializes the class behavior.
        /// </summary>
        /// <param name="context"></param>
        public void Init(HttpApplication context)
        {
            context.PostAcquireRequestState += new EventHandler(this.OnEnter);
            context.PostRequestHandlerExecute += new EventHandler(this.OnLeave);
        }

        private void OnEnter(object source, EventArgs eventArg)
        {
            try
            {
                System.Web.HttpApplication app = (HttpApplication)source;
                if (app.Context.Session != null)
                {
                    SessionOnDemandController.CreateInstance(CachingConfiguration.Current.SessionOnDemandConfig.IsEnabled);
                }
            }
            catch (Exception oError)
            {
                if (oError.GetType() == typeof(WebException))
                    if (((WebException)oError).Status == WebExceptionStatus.ProtocolError)
                        throw oError;
            }
        }

        private void OnLeave(object source, EventArgs eventArg)
        {
            try
            {
                System.Web.HttpApplication app = (HttpApplication)source;
                if (app.Context.Session != null)
                {
                    if (SessionOnDemandController.Current != null)
                    {
                        //sync the data was demanded
                        if (!app.Context.Session.IsReadOnly)
                            SessionOnDemandController.Current.SyncWithStorage();

                        //determine if we need to renew expiration DT
                        DateTime mustRenewStamp = DateTime.UtcNow.AddMinutes(-CachingConfiguration.SessionOnDemandRenewFlexibilityInterval);
                        DateTime lastRenew = mustRenewStamp;
                        object tmp = FlexiCache.RuntimeContext.SessionData["SessionOnDemandLastRenew"];
                        if (tmp != null)
                            lastRenew = (DateTime)tmp;
                        bool shouldRenew = (lastRenew <= mustRenewStamp);
                        //renew expiration DT for all items
                        if (shouldRenew)
                        {
                            FlexiCache.RuntimeContext.SessionData["SessionOnDemandLastRenew"] = DateTime.UtcNow;
                            SessionOnDemandController.Current.Renew();
                        }
                    }
                }
            }
            catch (Exception oError)
            {
                if (oError.GetType() == typeof(WebException))
                    if (((WebException)oError).Status == WebExceptionStatus.ProtocolError)
                        throw oError;
            }
        }
    }
}
